package com.factory.test.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;


/**
 * 彩色测试View
 */
public class MulticolorView extends View {

    private Context context;
    private boolean reverse = false;

    public MulticolorView(Context context) {
        super(context);
        init(context);
    }

    public MulticolorView(Context context, boolean reverse) {
        super(context);
        this.reverse = reverse;
        init(context);
    }

    public MulticolorView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MulticolorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public MulticolorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }


    private Paint[] paints;

    /**
     * todo 色阶测试, 数量必须是屏幕高度的整除数, 否则绘制出来会有色差!
     */
    private int[] colors = new int[]{
            Color.BLACK,
            Color.DKGRAY,
            Color.GRAY,
            Color.LTGRAY,
            Color.WHITE,
            Color.RED,
            Color.GREEN,
            Color.BLUE,
            Color.YELLOW,
            Color.CYAN,
            //Color.MAGENTA
    };
    private int count = colors.length;
    private int widthPixel;
    private int heightPixel;


    public int[] reverseArray(int[] colorArray){
        for (int i = 0; i <= colorArray.length / 2 - 1; i++) {
            int temp1 = colorArray[i];
            int temp2 = colorArray[colorArray.length - i - 1];
            colorArray[i] = temp2;
            colorArray[colorArray.length - i - 1] = temp1;
        }
        return colorArray;
    }

    private void init(Context context){
        this.context = context;
        DisplayMetrics outMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(outMetrics);
        widthPixel = outMetrics.widthPixels;
        heightPixel = outMetrics.heightPixels;

        paints = new Paint[this.count];
        if(reverse){
            reverseArray(colors);
        }
        for (int i = 0; i < count; i++) {
            paints[i] = new Paint();
            paints[i].setColor(colors[i]);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < count; i++) {
            canvas.drawRect(0, heightPixel / count * i, widthPixel, heightPixel / count * (i + 1), paints[i]);
        }
    }
}
